package com.novabluetooth.services.lbxd;
import java.io.StringReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import org.xmlpull.v1.XmlPullParser;

import com.ecg.bean.Exam_item_info;
import com.ecg.bean.Patient_info;
import com.ecg.device.DX12ECG;
import com.ecg.mysurfaceview.MySurfaceView;
import com.health.viewscontrols.NovaApplication;
import com.health.R;
import com.health.tablebean.ARCHIVE_BASEINFO;
import com.health.tablebean.SBCL_DATA;
import com.nova.BaseActivity;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.util.Xml;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
public class LBXD_DisplayWaveActivity extends BaseActivity {
	//控件的声明
	private MySurfaceView mySurfaceView;
	private Button btnCollect,btnCancle;
	private DX12ECG mCollect;//采集工具的对象
	private Thread myThread = null;
	private boolean isSampleing = true;//判断是否正在采集过程当中，防止线程无法终止
	private boolean isSave = false;//由于有两个线程在独立跑，为了避免提示保存数据对话框
									//弹出多次，声明一个变量来控制只弹出一次
	private Patient_info patient =null;
	//<isDemo>TRUE 是否是demo
	private static String paraXML = "<?xml version='1.0' encoding='utf-8' standalone='yes' ?>"
			 + "<root>"
			 + "<isDemo>TRUE" 
			 + "</isDemo>"
			 + "<saveFile>FALSE</saveFile>"
			 + "</root>";
	private ARCHIVE_BASEINFO userInfo = null;
	private String IDCARD = "";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.lbxd_displaywave);
		userInfo = NovaApplication.getUserInfo();
		if (userInfo != null) {
			IDCARD = userInfo.getIDCARD();
			if (TextUtils.isEmpty(IDCARD)) {
				return;
			}
		}
		initView();
		doSomething();
	}
	
	Handler hd = new Handler(){
		public void handleMessage(Message msg) {
			btnCollect.setText(msg.arg1 + "s");//可以显示采集了多少秒
			if(mCollect.isCollectedComplete() && !isSave){
				isSave = true;
				new AlertDialog.Builder(LBXD_DisplayWaveActivity.this)
						.setTitle("系统提示")
						.setMessage("采集数据完成，是否保存数据到指定目录")
						.setNegativeButton("取消",
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int which) {
									}
								})
						.setPositiveButton("保存",
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int which) {

										final ProgressDialog mDialog = new ProgressDialog(
												LBXD_DisplayWaveActivity.this);
										mDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
										mDialog.setMessage("正在保存采集数据");
										mDialog.setIndeterminate(false);
										mDialog.setCancelable(false);
										final Handler mHandler = new Handler() {
											public void handleMessage(
													Message msg) {
												mDialog.dismiss();
												if (msg.what == 100) {
													Log.e("RInfo", "诊断结果:" + mCollect.getResult());
													String xml = mCollect.getResultParameter();
													Param para = new Param();
													para = getParam(xml);
													Log.e("RInfo","诊断参数:" + xml);
													
													Exam_item_info mInfo = new Exam_item_info();
													mInfo = mCollect.getItem_info();
													/*Intent intent = new Intent();
													intent.setClassName(getApplication(), "com.ecg.view.EcgWaveActivity");
													intent.putExtra("examItemInfo", mInfo);
													startActivity(intent);*/

													
													String str_img_url_jpeg = mCollect.getJPGURL();
													if(str_img_url_jpeg!=null){
														showTextDialog("保存成功");
														//TODO 心率值暂时无法模拟
														saveData(str_img_url_jpeg, mCollect.getResult(),"");
														Intent intent = new Intent(getApplicationContext(), ShowPicActivity.class);
														intent.putExtra("JPG_URL", str_img_url_jpeg);
														startActivity(intent);
														LBXD_DisplayWaveActivity.this.finish();
													}
													
													
													
												} else {
													showTextDialog("保存失败");
												}
											};
										};
										new Thread() {
											boolean flag = false;

											public void run() {
												// 保存dat文件是否成功
												flag = mCollect.saveFile("4eb6543c");//诊断码   pad5:4eb6543c  wtt:f6324b11  txw:7b791ea8
												if (flag) {
													// 是否保存dcm文件成功
													if (mCollect.saveToJPG()) {
														mHandler.sendEmptyMessage(100);
													} else {
														mHandler.sendEmptyMessage(101);
													}
												} else {
													mHandler.sendEmptyMessage(101);
												}
											};
										}.start();
										mDialog.show();
									}
								}).show();
			}
		};
	};
	public void initView(){
		//控件的绑定
		btnCollect = (Button) findViewById(R.id.btnCaiJi);
		btnCancle = (Button) findViewById(R.id.btnCancle);
		mySurfaceView = (MySurfaceView) findViewById(R.id.surfaceViewWave);
		initPatInfo();
		mCollect = new DX12ECG(this, mySurfaceView, patient,paraXML);//采集对象的初始化
		mCollect.initSurfaceView(0, 0, 0, 0, 0, 0);
		mCollect.show();
		
	}
	
	private void initPatInfo(){
		patient=new Patient_info();
		if(userInfo!=null){
			patient.setPatient_id(userInfo.getIDCARD());//病人身份证号
			patient.setPatient_name(userInfo.getCUSTOMERNAME());//病人姓名
			patient.setRace(userInfo.getIDCARD()); //身份证号
			
			String str_sex= userInfo.getSEX();
			   String str_sex_name="";
				/** 1:男,2:女,0:未知的性别,9:未说明的性别 */
			   if(str_sex.equals("1")){
				   str_sex_name="男";
			   }else  if(str_sex.equals("2")){
				   str_sex_name="女";
			   }/*else  if(str_sex.equals("0")){
				   str_sex_name="未知的性别";
			   }else  if(str_sex.equals("9")){
				   str_sex_name="未说明的性别";
			   }
			   */
			   
			patient.setSex(str_sex_name);
			patient.setDate_of_birth(userInfo.getBIRTHDAY());
		}
		
	}
	
	
	//做一些操作
	
	private void doSomething(){
		//响应点击开始采集按钮事件
		btnCollect.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				
				mCollect.start();
				isSampleing = true;
				isSave = false;
				myThread = new Thread(){//开启线程进行监听采集的进程
					@Override
					public void run() {
						while(isSampleing){
							//判断采集是否完成
							if(mCollect.isCollectedComplete()){
								isSampleing = false;
							}
							Message msg = new Message();
							msg.arg1 = mCollect.getTime();//获取采集时间
							hd.sendMessage(msg);
						}
					}
				};
				myThread.start();
			}
		});
		
		//响应取消采集按钮事件
		btnCancle.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mCollect.end();
			}
		});
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		isSampleing = false;
		myThread = null;
		mCollect.closeDevice();
	}
	
	private Param getParam(String xml) {

		Param para = null;
		// 由android.util.Xml创建一个XmlPullParser实例
		XmlPullParser parser = Xml.newPullParser();
		try {
			parser.setInput(new StringReader(xml));

			int eventType = parser.getEventType();
			while (eventType != XmlPullParser.END_DOCUMENT) {
				String str = parser.getName();

				switch (eventType) {
				case XmlPullParser.START_DOCUMENT:
					para = new Param();
					break;
				case XmlPullParser.START_TAG:
					if (parser.getName().equals("name")) {
						// Log.d(TAG, parser.getText());
						eventType = parser.next();
						// Log.d(TAG, parser.getText());
						//Log.e("error", parser.getText());
						if (parser.getText().equals("心率")) {
							parser.next();
							parser.next();
							parser.next();
							Log.e("error", parser.getText());
							para.setHR(parser.getText());
						} else if (parser.getText().equals("P间期")) {
							parser.next();
							parser.next();
							parser.next();
							para.setP(parser.getText());
						} else if (parser.getText().equals("PR间期")) {
							parser.next();
							parser.next();
							parser.next();
							para.setPR(parser.getText());
						} else if (parser.getText().equals("PRS间期")) {
							parser.next();
							parser.next();
							parser.next();
							para.setPRS(parser.getText());
						} else if (parser.getText().equals("QT间期")) {
							parser.next();
							parser.next();
							parser.next();
							para.setQT(parser.getText());
						} else if (parser.getText().equals("QTc间期")) {
							parser.next();
							parser.next();
							parser.next();
							para.setQTc(parser.getText());
						} else if (parser.getText().equals("P电轴")) {
							parser.next();
							parser.next();
							parser.next();
							para.setPValue(parser.getText());
						} else if (parser.getText().equals("QRS电轴")) {
							parser.next();
							parser.next();
							parser.next();
							para.setQRSValue(parser.getText());
						} else if (parser.getText().equals("T电轴")) {
							parser.next();
							parser.next();
							parser.next();
							para.setTValue(parser.getText());
						} else if (parser.getText().equals("RV5幅值")) {
							parser.next();
							parser.next();
							parser.next();
							para.setRV5(parser.getText());
						} else if (parser.getText().equals("RV6幅值")) {
							parser.next();
							parser.next();
							parser.next();
							para.setRV6(parser.getText());
						} else if (parser.getText().equals("SV1幅值")) {
							parser.next();
							parser.next();
							parser.next();
							para.setSV1(parser.getText());
						} else if (parser.getText().equals("SV2幅值")) {
							parser.next();
							parser.next();
							parser.next();
							para.setSV2(parser.getText());
						}

					}
					break;
				case XmlPullParser.END_TAG:
					break;
				}
				// Log.d(TAG, parser.getText());
				eventType = parser.next();
				// Log.d(TAG, parser.getText());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return para;
	}
	
	/**
	 * 保存结果到数据库
	 * @param imgUrl
	 * @param str_result
	 * @author 王婷婷
	 * @date 2016年1月15日 下午12:03:39
	 */
	private void saveData(String imgUrl,String str_result,String heartRate){
		UUID uuidECG = UUID.randomUUID();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String dateECG = df.format(new Date());
		Log.e("eeeeeeeeeeeeeeeee2222",str_result );
		saveCLData("理邦心电", "理邦心电", "心电图片", imgUrl, "心电图片", uuidECG.toString(), IDCARD, dateECG);
		saveCLData("理邦心电", "理邦心电", "心电诊断结果", str_result, "心电诊断结果", uuidECG.toString(), IDCARD, dateECG);
		saveCLData("理邦心电", "理邦心电", "心率", str_result, "心率", uuidECG.toString(), IDCARD, dateECG);

	}
	/**
	 * 保存测量数据
	 * @param device_name
	 * @param device_type
	 * @param cl_type
	 * @param cl_value
	 * @param cl_type_name
	 * @param GUID
	 * @param IDCARD
	 * @param cl_time
	 * @author 王婷婷
	 * @date 2016年1月15日 上午11:52:10
	 */
	public void saveCLData(String device_name, String device_type, String cl_type, String cl_value, String cl_type_name,
			String GUID, String IDCARD, String cl_time) {
		SBCL_DATA sbcl_Data = new SBCL_DATA();
		sbcl_Data.setDEVICE_NAME(device_name);
		sbcl_Data.setDEVICE_TYPE(device_type);
		sbcl_Data.setCL_TYPE(cl_type);
		sbcl_Data.setCL_VALUE(cl_value);
		sbcl_Data.setCL_TYPE_NAME(cl_type_name);
		sbcl_Data.setGUID(GUID);
		sbcl_Data.setIDCARD(IDCARD);
		sbcl_Data.setCL_TIME(cl_time);
		sbcl_Data.setIS_UPDATE("Y");
		NovaApplication.fdbmanger.save(sbcl_Data);
	}

	 
}
